<template>
  <a-space direction="vertical" fill>
    <a-space>
      <a-button type="primary" @click="handleCopy">
        <template #icon>
          <icon-copy />
        </template>
        复制
      </a-button>
      <a-button type="primary" @click="handleDownload">
        <template #icon>
          <icon-download />
        </template>
        下载
      </a-button>
    </a-space>
    <a-scrollbar :style="kOpenRawStyle">
      <k-code ref="docketRef" v-model="docketString" language="json" />
    </a-scrollbar>
  </a-space>
</template>

<script setup lang="ts">
  import { Message } from '@arco-design/web-vue'
  import { js_beautify as JsBeau } from 'js-beautify'
  import fileDownload from 'js-file-download'
  import { defaultProps, documentInjectionKey, IDocumentProps } from '@/views/document/types'
  import { objArray2obj } from '@/utils/tools'

  // 组件名称
  defineOptions({ name: 'OpenApi' })

  const openApiSource = inject<IDocumentProps>(documentInjectionKey, defaultProps)
  const { summary, api } = openApiSource
  const { docket } = useKnifeStore()
  const openApiRaw = { ...docket }
  const find = Object.entries(openApiRaw.paths).find((x) => x[0] === api)
  openApiRaw.paths = objArray2obj(find)

  const docketString = computed(() => JsBeau(JSON.stringify(openApiRaw)))
  // 计算 openRaw内容显示高度
  const { tabBar } = storeToRefs(useAppStore())

  const kOpenRawStyle = computed(() => {
    const subtract = tabBar.value ? 160 : 116
    return {
      'height': `calc(100vh - ${subtract}px)`,
      'overflow': 'auto',
      'padding-bottom': '12px'
    }
  })

  // 复制
  const handleCopy = async () => {
    const { copy } = useClipboard()
    await copy(docketString.value)
    Message.success('复制OpenApi成功')
  }
  // 下载
  const downloadName = ref(`${summary}-OpenAPI.json`)
  const handleDownload = () => {
    const content = new Blob([docketString.value], { type: 'text/plain;charset=utf-8' })
    fileDownload(content, downloadName.value)
  }
</script>

<style scoped></style>
